<template>
  <el-dialog
    top="30px"
    width="80%"
    append-to-body
    :visible.sync="visible"
    :close-on-click-modal="false"
    :before-close="beforeClose"
  >
    <el-button
      size="small"
      icon="el-icon-printer"
      class="mb-3"
      v-if="viewMode || approvalRow.editable === 0"
      @click="printPage"
    >
      打印
    </el-button>
    <div :id="printId">
      <h4 class="table-title" v-if="!isBankOrg">项目审批表</h4>
      <div class="table-desc">
        本次审批共 {{ projectCount }} 个项目，
        <span v-if="!isBankOrg">涉及银行 {{ bankCount }} 个，</span>
        金额人民币 {{ fundsCount }} 万元。
      </div>
      <table
        class="table table-bordered table-sm vertical-align-middle"
        v-if="!isBankOrg"
        v-loading="dataLoading"
      >
        <colgroup>
          <col width="10%" />
          <col width="10%" />
          <col width="10%" />
          <col width="10%" />
          <col width="10%" />
          <col width="10%" />
          <col width="10%" />
          <col width="10%" />
          <col width="10%" />
          <col width="10%" />
        </colgroup>
        <tbody>
          <tr>
            <td colspan="2" class="text-center font-weight-bold">项目经办人意见</td>
            <td colspan="8" class="input-td">
              <div class="p-2 approval-opinion">{{ approvalRow.res_option_point }}</div>
              <sign-cmpt
                :sign-name="approvalRow.res_person_point"
                :sign-date="approvalRow.res_date_point"
              ></sign-cmpt>
            </td>
          </tr>
          <tr>
            <td colspan="2" class="text-center font-weight-bold">业务部负责人初审意见</td>
            <td colspan="8" class="input-td">
              <el-input
                v-if="approvalRow.editable === 1"
                v-model="editForm.res_option_bus"
                placeholder="请填写意见"
              ></el-input>
              <div v-else class="p-2 approval-opinion">{{ approvalRow.res_option_bus }}</div>
              <sign-cmpt
                :sign-name="approvalRow.res_person_bus"
                :sign-date="approvalRow.res_date_bus"
              ></sign-cmpt>
            </td>
          </tr>
          <tr>
            <td colspan="2" class="text-center font-weight-bold">风险经理意见</td>
            <td colspan="8" class="input-td">
              <el-input
                v-if="approvalRow.editable === 2"
                v-model="editForm.res_option_risk_point"
                placeholder="请填写意见"
              ></el-input>
              <div v-else class="p-2 approval-opinion">{{ approvalRow.res_option_risk_point }}</div>
              <sign-cmpt
                :sign-name="approvalRow.res_person_risk_point"
                :sign-date="approvalRow.res_date_risk_point"
              ></sign-cmpt>
            </td>
          </tr>
          <tr>
            <td colspan="2" class="text-center font-weight-bold">风险部负责人复审意见</td>
            <td colspan="8" class="input-td">
              <el-input
                v-if="approvalRow.editable === 3"
                v-model="editForm.res_option_risk"
                placeholder="请填写意见"
              ></el-input>
              <div v-else class="p-2 approval-opinion">{{ approvalRow.res_option_risk }}</div>
              <sign-cmpt
                :sign-name="approvalRow.res_person_risk"
                :sign-date="approvalRow.res_date_risk"
              ></sign-cmpt>
            </td>
          </tr>
          <template>
            <tr v-for="(item, index) in reviewData" :key="index">
              <td
                colspan="2"
                v-if="index === 0"
                :rowspan="index === 0 ? reviewData.length : 1"
                class="text-center font-weight-bold"
              >
                评审会意见
              </td>
              <td colspan="8" class="input-td">
                <div class="d-flex p-2" v-if="item.editable">
                  <c-radio-group
                    :options="enumReviewType"
                    v-model="item.approval_status"
                  ></c-radio-group>
                  <div v-if="+item.approval_status !== 1" class="border rounded mt-2 w-75">
                    <el-input v-model="item.approval_option" placeholder="请填写意见"></el-input>
                  </div>
                </div>
                <div v-else class="px-2 pt-2 approval-opinion">
                  {{ enumReviewType[item.approval_status] || '' }}
                  {{ item.approval_option ? `：${item.approval_option}` : '' }}
                </div>
                <div :class="item.editable ? 'bg-input' : ''">
                  <sign-cmpt
                    :sign-name="item.approval_person_name"
                    :sign-date="item.approval_time"
                  ></sign-cmpt>
                </div>
              </td>
            </tr>
          </template>
          <tr>
            <td colspan="2" class="text-center font-weight-bold">评审会主任意见</td>
            <td colspan="8" class="input-td">
              <el-input
                v-if="approvalRow.editable === 5"
                v-model="editForm.res_option_corp"
                placeholder="请填写意见"
              ></el-input>
              <div v-else class="p-2 approval-opinion">{{ approvalRow.res_option_corp }}</div>
              <sign-cmpt
                :sign-name="approvalRow.res_person_corp"
                :sign-date="approvalRow.res_date_corp"
              ></sign-cmpt>
            </td>
          </tr>
          <tr v-if="!isViewMode && approvalRow.editable > 0">
            <td colspan="10">
              <div class="text-center">
                <el-button
                  type="primary"
                  class="btn-long"
                  :loading="loading"
                  @click="handleApply(1)"
                >
                  确定
                </el-button>
                <el-button
                  v-if="approvalRow.editable === 6"
                  type="primary"
                  class="btn-long"
                  :loading="loading"
                  @click="handleApply(2)"
                >
                  拒绝
                </el-button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
      <table
        class="table table-bordered table-sm vertical-align-middle text-center"
        v-loading="dataLoading"
      >
        <colgroup>
          <col width="10%" />
          <col width="10%" />
          <col width="10%" />
          <col width="10%" />
          <col width="10%" />
          <col width="10%" />
          <col width="10%" />
          <col width="10%" />
          <col width="10%" />
          <col width="10%" />
        </colgroup>
        <tbody>
          <tr>
            <td colspan="10">
              <div class="text-center font-weight-bold py-2">审批项目明细</div>
            </td>
          </tr>
          <tr class="font-weight-bold">
            <td>借款人/担保客户</td>
            <td>客户类型</td>
            <td>主营产业</td>
            <td>联系电话</td>
            <td>贷款银行</td>
            <td>放款日/拟担保起始日</td>
            <td>到期日</td>
            <td>贷款期限(月)</td>
            <td>贷款金额/拟担保金额(万元)</td>
            <td>借款用途</td>
          </tr>
          <tr v-for="item in tableData" :key="item.customer_related_id">
            <td>{{ item.customer_name }}</td>
            <td>{{ item.org_class_name }}</td>
            <td>{{ item.main_business }}</td>
            <td>{{ item.corp_phone }}</td>
            <td>{{ item.bank_name }}</td>
            <td>{{ item.loadDate }}</td>
            <td>{{ item.loadEndDate }}</td>
            <td>{{ item.warranty_period }}</td>
            <td>{{ item.warranty_amount }}</td>
            <td>{{ item.funds_use_dir }}</td>
          </tr>
          <template v-if="openMore">
            <tr v-for="item in moreData" :key="item.customer_related_id">
              <td>{{ item.customer_name }}</td>
              <td>{{ item.org_class_name }}</td>
              <td>{{ item.main_business }}</td>
              <td>{{ item.corp_phone }}</td>
              <td>{{ item.bank_name }}</td>
              <td>{{ item.loadDate }}</td>
              <td>{{ item.loadEndDate }}</td>
              <td>{{ item.warranty_period }}</td>
              <td>{{ item.warranty_amount }}</td>
              <td>{{ item.funds_use_dir }}</td>
            </tr>
          </template>
        </tbody>
      </table>
      <div v-if="viewMode" class="d-flex">
        <div class="flex-1 ml-5">
          <div class="my-5">申报银行（签章）：</div>
          <div class="my-5">经办人：</div>
          <div class="my-4">日期：</div>
        </div>
        <div class="flex-1 ml-5">
          <div class="my-5">担保公司（签章）：</div>
          <div class="my-5">经办人：</div>
          <div class="my-4">日期：</div>
        </div>
      </div>
    </div>

    <el-button v-if="moreData.length && !openMore" type="text" @click="openMore = true">
      查看更多
    </el-button>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { getStaff } from '@/common/api/auth'
import { printA4 } from '@vimi/utils-tool'
import { dateFormat } from '@/common/utils/common'

const enumEditPerson = {
  1: {
    status: 'res_status_bus',
    option: 'res_option_bus',
    person: 'res_person_bus',
    date: 'res_date_bus',
  },
  2: {
    status: 'res_status_risk_point',
    option: 'res_option_risk_point',
    person: 'res_person_risk_point',
    date: 'res_date_risk_point',
  },
  3: {
    status: 'res_status_risk',
    option: 'res_option_risk',
    person: 'res_person_risk',
    date: 'res_date_risk',
  },
  5: {
    status: 'res_status_corp',
    option: 'res_option_corp',
    person: 'res_person_corp',
    date: 'res_date_corp',
  },
}

export default {
  components: {
    'sign-cmpt': {
      functional: true,
      props: {
        signName: {
          type: String,
          default: '',
        },
        signDate: {
          type: String,
          default: '',
        },
      },
      render: (h, ctx) =>
        h(
          'div',
          {
            class: 'row justify-content-end p-2',
          },
          [
            h('div', { class: 'col-4' }, `签字：${ctx.props.signName}`),
            h(
              'div',
              { class: 'col-4' },
              `日期：${dateFormat(ctx.props.signDate, 'yyyy年MM月dd日')}`
            ),
          ]
        ),
    },
  },
  props: {
    visible: Boolean,
    approvalRow: {
      type: Object,
      default: () => ({}),
    },
    viewMode: Boolean,
  },
  data() {
    return {
      dataLoading: false,
      loading: false,
      tableName: 'datum_one_county_industry',
      reviewTableName: 'review_approval',
      batchTableName: 'review_approval_batch',
      tableData: [],
      moreData: [],
      openMore: false,
      reviewData: [],
      batchId: '',
      editForm: {
        res_option_bus: '',
        res_option_risk_point: '',
        res_option_risk: '',
        res_option_corp: '',
      },
      enumReviewType: {
        1: '同意',
        2: '否决',
        3: '复议',
        4: '有条件同意',
      },
      resCount: 0,
      reviewCount: 0,

      // 统计数
      projectCount: 0,
      bankCount: 0,
      fundsCount: 0,
    }
  },
  computed: {
    ...mapGetters(['user', 'userId', 'job', 'org', 'clientId']),
    isBankOrg() {
      return this.org.orgClass === 'org_bank'
    },
    isViewMode() {
      return this.viewMode
    },
    busVisible() {
      return +this.approvalRow.res_status_bus === 1 || this.approvalRow.editable === 1
    },
    riskPointVisible() {
      return +this.approvalRow.res_status_risk_point === 1 || this.approvalRow.editable === 2
    },
    riskVisible() {
      return +this.approvalRow.res_status_risk === 1 || this.approvalRow.editable === 3
    },
    resVisible() {
      const hasReviewSign = this.reviewData.length > 0
      return (
        +this.approvalRow.res_status_risk === 1 &&
        +this.approvalRow.res_status_bus === 1 &&
        (this.isViewMode ? hasReviewSign : this.needMySign || hasReviewSign)
      )
    },
    corpVisible() {
      return +this.approvalRow.res_status_corp === 1 || this.approvalRow.editable === 5
    },
    needMySign() {
      return this.approvalRow.status === 5 && this.user.isApprovalRep === 1
    },
    printId() {
      return 'print-hnd-approval-pf2wp'
    },
  },
  watch: {
    approvalRow: {
      handler: function (val) {
        this.batchId = val.review_approval_batch_id
        this.initForm()
        this.getData()
      },
      immediate: true,
      deep: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    beforeClose() {
      Object.keys(this.editForm).forEach(key => {
        this.editForm[key] = ''
      })
      this.tableData = []
      this.moreData = []
      this.reviewData = []
      this.loading = false
      this.dataLoading = false
      this.openMore = false
      this.resCount = 0
      this.reviewCount = 0
      this.$emit('update:visible', false)
    },
    async getData() {
      if (!this.batchId) return

      this.dataLoading = true
      const [[res1, res2, res3]] = await this.$utils.promise(
        Promise.all([this.getApprovalList(), this.getReviewList(), this.getResPerson()])
      )
      this.dataLoading = false

      const { status } = this.approvalRow
      const projectList = ((res1 && res1.data) || []).map(this.dataAdapter)

      // 统计数
      this.projectCount = projectList.length
      let bankCount = 0
      let fundsCount = 0
      let banks = {}
      for (const project of projectList) {
        const bankId = project.bank_id || project.bank_name || 'none'
        if (!banks[bankId]) {
          banks[bankId] = 1
          bankCount++
        }
        fundsCount += +(project.warranty_amount || 0)
      }
      this.bankCount = bankCount
      this.fundsCount = Math.round(fundsCount * 100) / 100
      this.tableData = projectList.splice(0, 10)
      this.moreData = projectList

      // 审批委员会成员
      const reviewList = (res2 && res2.data) || []
      this.reviewCount = reviewList.length
      this.resCount = res3.length

      this.reviewData = reviewList.map(item => {
        item.editable = status === 5 && item.approval_person === this.userId

        const indexInAll = res3.findIndex(it => it.userId === item.approval_person)
        if (indexInAll > -1) {
          res3.splice(indexInAll, 1)
        }

        return item
      })

      // 如果评审委员会审批完成或项目审查结束，则不用再添加空白行
      if (![6, 200, 300].includes(status)) {
        // 如果是自己还没填写意见，把自己的位置放在已审批的下一行
        res3.forEach(item => {
          item.editable = this.needMySign && item.userId === this.userId
        })
        res3.sort((a, b) => (b.editable ? 1 : -1))

        for (const person of res3) {
          this.reviewData.push({
            approval_person: person.userId,
            approval_option: '',
            approval_status: person.editable ? '1' : '',
            editable: person.editable,
          })
        }
      }
    },
    getApprovalList() {
      const params = {
        'review_approval_batch_id.eq': this.batchId,
      }
      if (this.isBankOrg) {
        params['bank_code.endlike'] = this.org.orgCode
      }

      return this.$api.getData(this.$serviceName, this.tableName, params, this.order)
    },
    getResPerson() {
      return getStaff().then(res => {
        return ((res && res.data) || []).filter(it => +it.isApprovalRep === 1)
      })
    },
    getReviewList() {
      return this.$api.getData(
        this.$serviceName,
        this.reviewTableName,
        {
          'review_approval_batch_id.eq': this.batchId,
        },
        {
          approval_time: 'asc',
        }
      )
    },
    dataAdapter(item) {
      item.loadDate = this.$utils.dateFormat(item.load_date, 'yyyy-MM-dd')
      item.loadEndDate = this.$utils.dateFormat(item.load_end_date, 'yyyy-MM-dd')
      return item
    },
    initForm() {
      ;['res_option_bus', 'res_option_risk_point', 'res_option_risk', 'res_option_corp'].forEach(
        key => {
          this.editForm[key] = this.approvalRow[key] || ''
        }
      )
    },
    handleApply(applyStatus) {
      const { editable } = this.approvalRow
      if (editable !== 4) {
        const person = enumEditPerson[this.approvalRow.editable]
        const opinion = this.editForm[person.option]
        if (!opinion) {
          return this.$message.error('请填写意见')
        }
        this.$utils.msgbox({
          message: `确定${applyStatus === 1 ? '审核' : '拒绝'}?`,
          type: 'info',
          beforeClose: () => this.putApproval(applyStatus),
        })
      } else if (editable === 4) {
        const item = this.reviewData.find(it => it.editable)
        if (item) {
          let { approval_option: opinion, approval_status: status, review_approval_id: id } = item
          if (+status === 1) {
            opinion = ''
          } else if (!opinion) {
            return this.$message.error('请输入意见')
          }

          const apis = [id ? this.putReview(id, opinion, status) : this.addReview(opinion, status)]
          const leftReviewCount = this.resCount - this.reviewCount
          if (leftReviewCount === 0 && +this.approvalRow.review_approval < 2) {
            apis.push(this.updateBatchResStatus(2))
          } else if (leftReviewCount === 1 && !id) {
            apis.push(this.updateBatchResStatus(2))
          } else if (this.reviewCount === 0) {
            apis.push(this.updateBatchResStatus(1))
          }

          this.$utils
            .msgbox({
              message: `确定审核?`,
              type: 'info',
              beforeClose: () => Promise.all(apis),
            })
            .then(res => {
              this.$emit('success', res)
              this.$message.success('提交成功！')
              this.beforeClose()
            })
            .catch(() => {
              this.$message.error('项目审查失败，请重试！')
            })
            .finally(() => {
              this.loading = false
            })
        }
      }
    },
    putApproval(status) {
      const date = this.$utils.dateFormat(new Date())

      const person = enumEditPerson[this.approvalRow.editable]
      if (!person) {
        throw new Error('no person')
      }

      const data = {
        [person.status]: status,
        [person.option]: this.editForm[person.option],
        [person.person]: this.user.realName,
        [person.date]: date,
      }

      this.loading = true
      return this.$api
        .updateData(this.$serviceName, this.batchTableName, this.batchId, data)
        .then(res => {
          this.$emit('success', res)
          this.$message.success('提交成功！')
          this.beforeClose()
        })
        .catch(() => {
          this.$message.error('项目审查失败，请重试！')
        })
        .finally(() => {
          this.loading = false
        })
    },
    putReview(id, opinion, approvalStatus) {
      return this.$api.updateData(this.$serviceName, this.reviewTableName, id, {
        approval_option: opinion,
        approval_status: approvalStatus,
        review_approval_batch_id: this.batchId,
      })
    },
    addReview(opinion, approvalStatus) {
      return this.$api.addData(this.$serviceName, this.reviewTableName, {
        approval_option: opinion,
        approval_job: this.job,
        approval_person: this.userId,
        approval_person_name: this.user.realName,
        approval_status: approvalStatus,
        approval_time: this.$utils.dateFormat(new Date()),
        review_approval_batch_id: this.batchId,
      })
    },
    updateBatchResStatus(status) {
      return this.$api.updateData(this.$serviceName, this.batchTableName, this.batchId, {
        review_approval: status,
      })
    },
    printPage() {
      printA4(
        document.getElementById(this.printId).innerHTML,
        `
        body {font-family: SimSun;}
        .text-indent{text-indent: 2rem;}
        .vertical-align-middle td {vertical-align: middle;}
        .table-title {
          font-size: 1.2rem;
          font-weight: bold;
          text-align: center;
          margin-bottom: 1rem;
        }
        .flex-1 { flex: 1; }
        .table-desc {
          text-indent: 2rem;
          margin: 2rem 0;
        }
      `
      )
    },
  },
}
</script>

<style lang="scss" scoped>
.vertical-align-middle td {
  vertical-align: middle;
}
.bg-input {
  background-color: #ffffee;
}
.table-title {
  font-size: 1.2rem;
  font-weight: bold;
  text-align: center;
  margin-bottom: 1rem;
}
.table-desc {
  text-indent: 2rem;
  margin: 2rem 0;
}
.approval-opinion {
  text-indent: 2rem;
  min-height: 2rem;
}
</style>
